//
//  NetworkClient.m
//  KD
//
//  Created by centling on 15/7/20.
//  Copyright (c) 2015年 centling. All rights reserved.
//

#import "NetworkClient.h"
#import "Global.h"
#import <AFNetworking.h>
#import <objc/runtime.h>
#import "NSDictionary+mutableDeepCopy.h"
#import "GlobalUtil.h"


@implementation NetworkClient

typedef NS_ENUM(NSInteger, RequestMethodType){
    RequestMethodTypePost = 1,
    RequestMethodTypeGet = 2,
    RequestMethodTypeDelete
};

/**
 *  对AFHTTPSessionManager启用单例模式
 *
 *  @return 单例
 */
+ (AFHTTPSessionManager*)sharedHTTPSessionManager{
    static AFHTTPSessionManager* mgr = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSURLSessionConfiguration* configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        configuration.timeoutIntervalForRequest = 2;
        NSURL* baseURL = [NSURL URLWithString:baseUrl];
        mgr = [[AFHTTPSessionManager alloc] initWithBaseURL:baseURL sessionConfiguration:configuration];
        mgr.requestSerializer = [AFJSONRequestSerializer serializer];
        mgr.responseSerializer = [AFJSONResponseSerializer serializer];
        [mgr.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    });
    return mgr;
}


+ (BOOL)checkRetry:(NSNumber*)retryCount{
    return retryCount.integerValue > 0;
}

+ (void)requestWihtMethod:(RequestMethodType)methodType
                         url:(NSString*)url
                      params:(NSDictionary*)params
                     success:(void (^)(id response))success
                     failure:(void (^)(NSError* err))failure
{
    
//    if(![AFNetworkReachabilityManager sharedManager].isReachable){
//        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"无网络，请重新连接" message:@"" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
//        [alert show];
//        return;
//    }
    
    AFHTTPSessionManager* mgr = [self sharedHTTPSessionManager];
    NSString *token =[[NSUserDefaults standardUserDefaults] objectForKey:TOKEN];
    NSMutableString *authHeader=[[NSMutableString alloc] initWithString:@"Bearer "];
    token.length>10?[authHeader appendString:token]:nil;
    [mgr.requestSerializer setValue:authHeader forHTTPHeaderField:@"Authorization"];
    
    
    //拼接标识Request的Key
    NSString* requestID = [NSString stringWithFormat:@"%@:%@", @(methodType), url];
    NSNumber* retryCount = objc_getAssociatedObject(mgr, [requestID UTF8String]);
    if (!retryCount) {
        retryCount = @(3);
    } else {
        retryCount = @(retryCount.integerValue - 1);
    }
    objc_setAssociatedObject(mgr, [requestID UTF8String], retryCount, OBJC_ASSOCIATION_COPY);
    switch (methodType) {
        case RequestMethodTypeGet:{
            //GET请求
            [mgr GET:url
          parameters:params
             success:^(NSURLSessionDataTask *task, id responseObject) {
                 NSDictionary* result = responseObject;
                 result = [result mutableDeepCopy];
                 [GlobalUtil deepCleanCollection:result];
                 if (success) {
                     success(result);
                     DDLogInfo(@"GET 请求成功 code:%@, msg %@", result[@"returnCode"], result[@"returnMsg"]);
                     DDLogDebug(@"输出请求地址------%@",url);
                 }
             }
             failure:^(NSURLSessionDataTask *task, NSError *error) {
                 if (error.code == kCFURLErrorTimedOut && [self checkRetry:retryCount]) {
                     [self requestWihtMethod:methodType
                                            url:url
                                         params:params
                                        success:success
                                        failure:failure];
                 } else {
                     objc_setAssociatedObject(mgr, [requestID UTF8String], nil, OBJC_ASSOCIATION_COPY);
                     failure(error);
                 }
             }];
        }
            break;
        case RequestMethodTypePost:
        {
            //POST请求
            [mgr POST:url
           parameters:params
              success:^(NSURLSessionDataTask *task, id responseObject) {
                  NSDictionary* result = responseObject;
                  result = [result mutableDeepCopy];
                  [GlobalUtil deepCleanCollection:result];
                  if (success) {
                      success(result);
                      DDLogInfo(@"POST 请求成功 code:%@, msg %@", result[@"returnCode"], result[@"returnMsg"]);
                      DDLogDebug(@"输出请求地址------%@",url);
                  }
              } failure:^(NSURLSessionDataTask *task, NSError *error) {
                  if (error.code == kCFURLErrorTimedOut && [self checkRetry:retryCount]) {
                      [self requestWihtMethod:methodType
                                             url:url
                                          params:params
                                         success:success
                                         failure:failure];
                  } else {
                      objc_setAssociatedObject(mgr, [requestID UTF8String], nil, OBJC_ASSOCIATION_COPY);
                      failure(error);
                  }
              }];
        }
            break;
        case RequestMethodTypeDelete:
        {
            //DELETE请求
            [mgr DELETE:url
             parameters:params
                success:^(NSURLSessionDataTask *task, id responseObject) {
                    NSDictionary* result = responseObject;
                    result = [result mutableDeepCopy];
                    [GlobalUtil deepCleanCollection:result];
                    if (success) {
                        success(result);
                        DDLogInfo(@"DELETE 请求成功 code:%@, msg %@", result[@"returnCode"], result[@"returnMsg"]);
                        DDLogDebug(@"输出请求地址------%@",url);
                    }
                } failure:^(NSURLSessionDataTask *task, NSError *error) {
                    if (error.code == kCFURLErrorTimedOut && [self checkRetry:retryCount]) {
                        [self requestWihtMethod:methodType
                                               url:url
                                            params:params
                                           success:success
                                           failure:failure];
                    } else {
                        objc_setAssociatedObject(mgr, [requestID UTF8String], nil, OBJC_ASSOCIATION_COPY);
                        failure(error);
                    }
                }];
        }
            break;
        default:
            break;
    }
}


//获取Token
+(void)getToken:(void (^)(Token *token))successBlock
        failure:(void (^)(NSError* err))failure{
    [NetworkClient requestWihtMethod:RequestMethodTypeGet
                                 url:@"auth/token.json?client_id=app&client_secret=000000"
                              params:nil
                             success:^(id response) {
                                 Token *token=[[Token alloc] initWithDictionary:(NSDictionary *)response error:nil];
                                 NSLog(@"%@",token);
                                 successBlock(token);
                             }
                             failure:^(NSError *err) {
                                 failure(err);
                             }];
}


//登录
+(void)login:(NSString *)userName
withPassword:(NSString *)password
     success:(void (^)(Token *token))success
     failure:(void (^)(NSError* err))failure{
    
    [NetworkClient requestWihtMethod:RequestMethodTypeGet
     
                                 url:[NSString stringWithFormat:@"member/login.json?userName=%@&password=%@",userName,password]
                              params:nil
                             success:^(id response) {
                                 NSLog(@"%@",response);
                             }
                             failure:^(NSError *err) {
                                 failure(err);
                             }];
}


@end
